import datetime
import uuid
import threading
import socket
import time
import ColorType
from collections import deque
from myoutput import *
import uart.honglieUart as hlu
import ctypes
User_Dict:dict={}
class User:
    #唯一的uuid码
    __uuid:uuid.UUID
    #uid,uuid前八位
    uid:str
    #已经连接的socket
    mysocket:socket.socket
    #socket地址
    address:str
    port:int
    #data缓冲区
    data_buf:str
    
    output_buffer:list
    #帧头
    socket_head:str
    #用户线程
    thread:threading.Thread
    #线程锁
    thread_flag:bool

    def get_uid_green(self) ->str:
        return add_color("[uid:{}]".format(self.uid),ColorType.Green)
    def __init__(self,conn:socket.socket,ip:str,port:int) -> None:
        global User_Dict
        #分配uid
        self.__uuid=uuid.uuid1()
        self.output_buffer=[]
        self.uid=str(self.__uuid)[:8]
        #绑定socket
        conn.settimeout(5)
        self.mysocket=conn
        self.address=ip
        self.port=port
        #加入字典中
        User_Dict[self.uid]=self
        #uid加入列表
        prompt_print(self.get_uid_green()
                    +add_color("connection establishment",ColorType.Yellow))
        self.thread=threading.Thread(name='Thread_Player_'+str(self.uid),
                                            target= Thread_User,
                                            args=(self,))
        #print("[{}] builded".format(self.player_thread.name))
        self.thread_start()#启动socket进程

    # def welcome(self):
    #     print("\033[93m"+"welcome [{}] join the game!".format(self.player_message)+"\033[0m")
    # def get_data(self,data_buf:str) -> str:
    #     self.player_data_buf=data_buf
    #     print_data=("\033[95m"
    #                 +"[{}]".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    #                 +"\033[0m"
    #                 +"\033[92m"
    #                 +"[player:{}]".format(self.player_message)
    #                 +"\033[0m"
    #                 +"[data:{}]".format(self.player_data_buf)
    #                 )
    #     return print_data
        
    # def print_data(self):
    #     print("\033[95m"
    #           +"[{}]".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    #           +"[player:{}]".format(self.player_message)
    #           +"[data:{}]".format(self.player_data_buf)
    #           +"\033[0m")
    def thread_start(self):
        self.thread_flag=True
        self.thread.start()


def Thread_User(user:User):
    global User_Dict
    #first_recv=user.mysocket.recv(1024).decode()
    #temp=first_recv.split(",")
    #user.group=int(temp[0])
    #user.name=temp[1]
    #prompt_print(add_color("welcome",ColorType.White)+" [{}] ".format(add_color(user.name,ColorType.Yellow)) +add_color("join the game!",ColorType.White))
    #first_send="uid,{}".format(user.uid)
    #user.mysocket.send(first_send.encode())
    while(user.thread_flag):
        try:  
            buf=user.mysocket.recv(1024)
        except:
            prompt_print(user.get_uid_green()+add_color("leave the server",ColorType.Red))
            break
        for k in User_Dict.keys():
            u:User=User_Dict[k]
            if(user!=u):
                u.output_buffer.append(user.uid.encode()+"SPLIT".encode()+buf+"OVER".encode())
        if(buf!=""):
            user.data_buf=buf
            #prompt_print(user.get_uid_green()+"data_buf:[{}]".format(user.data_buf))
            output="NULL".encode()
            if(len(user.output_buffer)!=0):
                output=bytes()
                for buffer in user.output_buffer:
                    buffer:bytes
                    output+=buffer
                user.output_buffer.clear()
            try:
                user.mysocket.send(output)
            except:
                prompt_print(user.get_uid_green()+add_color("leave the server",ColorType.Red))
                break
    user.mysocket.close()
    User_Dict.pop(user.uid)
    prompt_print(user.get_uid_green()+add_color("thread be killed!",ColorType.Red))
    #print("\033[91m[0mUUID:{} be killed!\033")


